package com.itheima.reggie.controller;

import com.itheima.reggie.common.R;
import com.itheima.reggie.pojo.User;
import com.itheima.reggie.service.UserService;
import com.itheima.reggie.utils.SMSUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.RandomStringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpSession;
import java.util.Map;

/**
 * 移动端用户管理
 */
@Slf4j
@RestController
@RequestMapping("user")
public class UserController {
    @Autowired
    private UserService userService;
    //发验证码
    @PostMapping("sendMsg")
    public R sendMsg(@RequestBody User user, HttpSession session){
        String phone = user.getPhone();
        String code = RandomStringUtils.random(4, false, true);
        SMSUtils.sendMessage(phone,code);
        //使用session保存验证码
        session.setAttribute(phone,code);
        log.info("验证码={}",code);
        return R.success("验证码发送成功");
    }
    //验证登录
    @PostMapping("login")
    public R login(@RequestBody Map<String,String> map,HttpSession session){
        String code = map.get("code");
        String phone = map.get("phone");
        String codeSession = (String) session.getAttribute(phone);
        if (!codeSession.equals(code)){
            return R.error("验证码错误");
        }
        //判断，如果是新用户，自动注册
        User user = userService.lambdaQuery()
                .eq(User::getPhone, phone)
                .one();
        if (user==null){
            user = new User();
            user.setPhone(phone);
            user.setStatus(1);
            //保存用户
            userService.save(user);
        }
        session.setAttribute("user",user.getId());
        return R.success(user);
    }
    //退出登录
    @PostMapping("loginout")
    public R loginOut(HttpSession session){
        session.invalidate();//销毁session
        return R.success("退出成功");
    }
}
